package cn.glinks.liuhe.activity;

import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.view.KeyEvent;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.OnClick;
import cn.glinks.liuhe.R;
import cn.glinks.liuhe.api.jsonbean.ParksInfo;
import cn.glinks.liuhe.api.jsonbean.UserInfo;
import cn.glinks.liuhe.app.AppApplication;
import cn.glinks.liuhe.app.AppConstant;
import cn.glinks.liuhe.base.BaseActivity;
import cn.glinks.liuhe.utils.ActTransAnimUtils;
import cn.glinks.liuhe.utils.DisplayUtils;
import cn.glinks.liuhe.utils.LogUtils;
import cn.glinks.liuhe.utils.ToastUtils;
import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.utils.ColorTemplate;
import java.util.ArrayList;
import java.util.List;

/**
 * Des:统计图表页面1
 *
 * @author MarsBlade of Cyh
 * @created 2017-03-21 14:43
 */
public class ChartOneActivity extends BaseActivity implements OnChartValueSelectedListener {

    @BindView(R.id.tv_title)
    TextView mTitleText;

    @BindView(R.id.tv_sum)
    TextView mSumText;

    @BindView(R.id.view_piechart)
    PieChart mPieChart;

    @BindView(R.id.tv_level_a)
    TextView mLevelAText;

    @BindView(R.id.tv_level_b)
    TextView mLevelBText;

    @BindView(R.id.tv_level_c)
    TextView mLevelCText;

    @BindView(R.id.tv_level_d)
    TextView mLevelDText;

    @BindView(R.id.tv_level_e)
    TextView mLevelEText;

    // 变量
    private UserInfo mUserInfo;
    private int mIndex = -1;
    private ParksInfo mParksInfo = null;
    private ParksInfo.ParksBean mParksBean = null;
    private PieData mPieData = null;
    private String mLevelName = "";

    // 字体文件
    private Typeface mTfRegular;
    private Typeface mTfLight;

    @Override
    public int getLayoutId() {
        return R.layout.activity_chart_1;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        // 加载字体
        mTfRegular = Typeface.createFromAsset(getAssets(), "OpenSans-Regular.ttf");
        mTfLight = Typeface.createFromAsset(getAssets(), "OpenSans-Light.ttf");
        // 获取传递过来的数据
        Bundle bundle = this.getIntent().getExtras();
        mIndex = bundle.getInt(AppConstant.BUNDLE_PARK_INDEX, -1);
        // 获取园区统计数据
        mParksInfo = ((AppApplication) getApplicationContext()).getStatisticData();
        if (mIndex >= 0) {
            mParksBean = mParksInfo.getParks().get(mIndex);
        } else {
            ToastUtils.showShort("加载数据失败");
        }
        // 加载数据
        showLabelDatas(mParksBean);
        mPieData = getChartData(mParksBean);

        // 旋转Root View(横屏处理)
        RelativeLayout rootLayout = (RelativeLayout)findViewById(R.id.rl_chart_1_root);
        int screenHeight = DisplayUtils.getScreenHeight(this);
        int screenWidth = DisplayUtils.getScreenWidth(this);
        FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) rootLayout.getLayoutParams();
        params.height = screenWidth;
        params.width = screenHeight;
        params.topMargin = (screenHeight - screenWidth) / 2;
        params.leftMargin = (screenWidth - screenHeight) / 2;
        rootLayout.setLayoutParams(params);
        rootLayout.setRotation(90);
        // 设置为透明状态栏
        SetTranslanteBar();
        // 加载用户信息
        mUserInfo = ((AppApplication) getApplicationContext()).getLoginUser();
        // 根据单位类型设置统计页面标题
        if (mUserInfo.getUser().getUnitCode().equals("S8001")) { // 富士康
            mTitleText.setText("富士康（"+mParksBean.getParkName().replace("园区", "")+"）园区");
        } else if (mUserInfo.getUser().getUnitCode().equals("Z6802")) { // 2017广西壮族自治区总工会驻粤务工农民工骨干培训班
            mTitleText.setText(mParksBean.getParkName()+"地区");
        } else {
            mTitleText.setText(mParksBean.getParkName());
        }
        mSumText.setText(mParksBean.getPop()+"人");
        // 初始化饼状图View
        initChartView();
    }

    /*--------------------------------------------------------------------------------
     *                          数据初始化函数
     ---------------------------------------------------------------------------------*/
    private void showLabelDatas(ParksInfo.ParksBean parksBean) {
        mLevelAText.setText("("+parksBean.getL3Sum()+"人,"
                +String.format("%.1f", parksBean.getL3Sum()*100.0f/parksBean.getTestSum())+"%)");
        mLevelBText.setText("("+parksBean.getL4Sum()+"人,"
                +String.format("%.1f", parksBean.getL4Sum()*100.0f/parksBean.getTestSum())+"%)");
        mLevelCText.setText("("+parksBean.getL2Sum()+"人,"
                +String.format("%.1f", parksBean.getL2Sum()*100.0f/parksBean.getTestSum())+"%)");
        mLevelDText.setText("("+parksBean.getL1Sum()+"人,"
                +String.format("%.1f", parksBean.getL1Sum()*100.0f/parksBean.getTestSum())+"%)");
        mLevelEText.setText("("+parksBean.getL5Sum()+"人,"
                +String.format("%.1f", parksBean.getL5Sum()*100.0f/parksBean.getTestSum())+"%)");
    }

    /*--------------------------------------------------------------------------------
     *                          饼状图初始化函数
     ---------------------------------------------------------------------------------*/
    /**
     * 构建PieData数据
     * @param parksBean
     */
    private PieData getChartData(ParksInfo.ParksBean parksBean) {
        int sum;
        PieEntry entry;
        List<PieEntry> list = new ArrayList<>();
        ArrayList<Integer> colors = new ArrayList<>();
        // 加载数据
        sum = parksBean.getL3Sum();
        if (sum > 0) {
            colors.add(ContextCompat.getColor(this, R.color.chart_level_A));
            entry = new PieEntry(sum, sum+"人", "合格");
            list.add(entry);
        }
        sum = parksBean.getL4Sum();
        if (sum > 0) {
            colors.add(ContextCompat.getColor(this, R.color.chart_level_B));
            entry = new PieEntry(sum, sum+"人", "可疑");
            list.add(entry);
        }
        sum = parksBean.getL2Sum();
        if (sum > 0) {
            colors.add(ContextCompat.getColor(this, R.color.chart_level_C));
            entry = new PieEntry(sum, sum+"人", "关注");
            list.add(entry);
        }
        sum = parksBean.getL1Sum();
        if (sum > 0) {
            colors.add(ContextCompat.getColor(this, R.color.chart_level_D));
            entry = new PieEntry(sum, sum+"人", "不合格");
            list.add(entry);
        }
        sum = parksBean.getL5Sum();
        if (sum > 0) {
            colors.add(ContextCompat.getColor(this, R.color.chart_level_E));
            entry = new PieEntry(sum, sum+"人", "无效");
            list.add(entry);
        }
        // 设置PieDataSet
        PieDataSet dataSet = new PieDataSet(list, "人数分类");
        dataSet.setSliceSpace(0f);// 设置扇形间隔
        dataSet.setSelectionShift(5f);// 设置选中扇形的突出显示偏移量
        dataSet.setDrawValues(false);// 设置是否显示y-values(即百分比)
        dataSet.setColors(colors);// 设置饼状图颜色序列
        // 设置PieData
        PieData data = new PieData(dataSet);
        data.setValueFormatter(new PercentFormatter());
        data.setValueTextSize(11f);
        data.setValueTextColors(colors);
        data.setValueTypeface(mTfRegular);

        return data;
    }

    /**
     * 初始化饼状图View
     */
    private void initChartView() {
        // 初始化图表
        mPieChart.setUsePercentValues(true);//设置显示成比例
        mPieChart.getDescription().setEnabled(false);
        mPieChart.setExtraOffsets(0.0f, 0.0f, 0.0f, 0.0f);
        mPieChart.setDragDecelerationFrictionCoef(0.95f);

        mPieChart.setCenterTextTypeface(mTfLight);
        mPieChart.setCenterTextColor(ColorTemplate.getHoloBlue());
        mPieChart.setCenterTextSize(18);
        mPieChart.setCenterText(mParksBean.getTestPop()+"人");

        mPieChart.setRotationAngle(270);//初始旋转角度
        mPieChart.setEntryLabelTextSize(13);//设置 Entry Label 的字体大小(dp)
        mPieChart.setRotationEnabled(true);//是否使能手动旋转
        mPieChart.setDrawCenterText(true);//饼状图中间是否可以添加文字

        mPieChart.setDrawHoleEnabled(true);//是否显示成圆环模式(即带有中心圆的环形图表)
        mPieChart.setHoleColor(Color.TRANSPARENT);//中心圆的背景颜色
        mPieChart.setHoleRadius(45f);//中心圆的半径(百分比)

        mPieChart.setTransparentCircleColor(Color.WHITE);//半透明圆环的颜色
        mPieChart.setTransparentCircleAlpha(110);//半透明圆环的透明度
        mPieChart.setTransparentCircleRadius(48f);//半透明圆环的半径(百分比),一般比中心圆半径多5f

        mPieChart.setHighlightPerTapEnabled(true);

        // add a selection listener
        mPieChart.setOnChartValueSelectedListener(this);

        mPieChart.setData(mPieData);

        // undo all highlights
        mPieChart.highlightValues(null);

        mPieChart.invalidate();

        mPieChart.animateY(1400, Easing.EasingOption.EaseInOutQuad);
        // mPieChart.spin(2000, 0, 360);

        //设置比例图
        Legend legend = mPieChart.getLegend();
        legend.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
        legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);
        legend.setOrientation(Legend.LegendOrientation.VERTICAL);
        legend.setDrawInside(false);
        legend.setEnabled(false);//设置禁用比例块
    }

    @Override
    public void onValueSelected(Entry e, Highlight h) {
        if (e == null) {
            return;
        }
        LogUtils.logd("VAL SELECTED" + "Value: " + e.getY() + ", xIndex: " + e.getX()
                + ", DataSet index: " + h.getDataSetIndex());
        // 判断数据是否为0
        mLevelName = (String)e.getData();
        String levelName = (String)e.getData();
        int sum = 0;
        if (levelName.equals("合格")) {
            sum = mParksBean.getL3Sum();
        } else if (levelName.equals("可疑")) {
            sum = mParksBean.getL4Sum();
        } else if (levelName.equals("关注")) {
            sum = mParksBean.getL2Sum();
        } else if (levelName.equals("不合格")) {
            sum = mParksBean.getL1Sum();
        } else if (levelName.equals("无效")) {
            sum = mParksBean.getL5Sum();
        }
        if (sum == 0) {
            return;
        }
        // 打包数据,传递并跳转到图表页面
        Bundle bundle = new Bundle();
        bundle.putInt(AppConstant.BUNDLE_PARK_INDEX, mIndex);
        bundle.putString(AppConstant.BUNDLE_PARK_LEVEL_NAME, levelName);
        ActTransAnimUtils.startActionFadeInFadeOut(ChartOneActivity.this, ChartTwoActivity.class, bundle);
    }

    @Override
    public void onNothingSelected() {
        LogUtils.logd("PieChart nothing selected");
        String levelName = "";
        // 判断是否前一次点击是否和当前取消点击一致
        if (mLevelName.length() == 0) {
            return;
        } else {
            levelName = mLevelName;
            mLevelName = "";
        }
        // 判断数据是否为0
        int sum = 0;
        if (levelName.equals("合格")) {
            sum = mParksBean.getL3Sum();
        } else if (levelName.equals("可疑")) {
            sum = mParksBean.getL4Sum();
        } else if (levelName.equals("关注")) {
            sum = mParksBean.getL2Sum();
        } else if (levelName.equals("不合格")) {
            sum = mParksBean.getL1Sum();
        } else if (levelName.equals("无效")) {
            sum = mParksBean.getL5Sum();
        }
        if (sum == 0) {
            return;
        }
        // 打包数据,传递并跳转到图表页面
        Bundle bundle = new Bundle();
        bundle.putInt(AppConstant.BUNDLE_PARK_INDEX, mIndex);
        bundle.putString(AppConstant.BUNDLE_PARK_LEVEL_NAME, levelName);
        ActTransAnimUtils.startActionFadeInFadeOut(ChartOneActivity.this, ChartTwoActivity.class, bundle);
    }



    /*--------------------------------------------------------------------------------
     *                          点击事件接口实现
     ---------------------------------------------------------------------------------*/
    // 返回
    @OnClick(R.id.iv_cancel)
    public void clickCancel() {
        // 返回
        ActTransAnimUtils.finishActionFadeOut(this);
    }

    // 左按键
    @OnClick(R.id.tv_left)
    public void clickLeft() {
        // 打包数据,传递并跳转到搜索页面
        Bundle bundle = new Bundle();
        bundle.putString(AppConstant.BUNDLE_PARK_NAME, mParksBean.getParkName());
        ActTransAnimUtils.startActionSlideRightToLeft(this, SearchActivity.class, bundle);
    }

    // 右按键
    @OnClick(R.id.tv_right)
    public void clickRight() {
        // 打包数据,传递并跳转到园区建议页面
        Bundle bundle = new Bundle();
        bundle.putString(AppConstant.BUNDLE_PARK_NAME, mParksBean.getParkName());
        ActTransAnimUtils.startActionSlideRightToLeft(this, ParkProposalActivity.class, bundle);
    }

    // 合格
    @OnClick(R.id.ll_level_a)
    public void clickLevelA() {
        if (mParksBean.getL3Sum() == 0) {
            return;
        }
        // 打包数据,传递并跳转到图表页面
        Bundle bundle = new Bundle();
        bundle.putInt(AppConstant.BUNDLE_PARK_INDEX, mIndex);
        bundle.putString(AppConstant.BUNDLE_PARK_LEVEL_NAME, "合格");
        ActTransAnimUtils.startActionFadeInFadeOut(ChartOneActivity.this, ChartTwoActivity.class, bundle);
    }

    // 可疑
    @OnClick(R.id.ll_level_b)
    public void clickLevelB() {
        if (mParksBean.getL4Sum() == 0) {
            return;
        }
        // 打包数据,传递并跳转到图表页面
        Bundle bundle = new Bundle();
        bundle.putInt(AppConstant.BUNDLE_PARK_INDEX, mIndex);
        bundle.putString(AppConstant.BUNDLE_PARK_LEVEL_NAME, "可疑");
        ActTransAnimUtils.startActionFadeInFadeOut(ChartOneActivity.this, ChartTwoActivity.class, bundle);
    }

    // 关注
    @OnClick(R.id.ll_level_c)
    public void clickLevelC() {
        if (mParksBean.getL2Sum() == 0) {
            return;
        }
        // 打包数据,传递并跳转到图表页面
        Bundle bundle = new Bundle();
        bundle.putInt(AppConstant.BUNDLE_PARK_INDEX, mIndex);
        bundle.putString(AppConstant.BUNDLE_PARK_LEVEL_NAME, "关注");
        ActTransAnimUtils.startActionFadeInFadeOut(ChartOneActivity.this, ChartTwoActivity.class, bundle);
    }

    // 不合格
    @OnClick(R.id.ll_level_d)
    public void clickLevelD() {
        if (mParksBean.getL1Sum() == 0) {
            return;
        }
        // 打包数据,传递并跳转到图表页面
        Bundle bundle = new Bundle();
        bundle.putInt(AppConstant.BUNDLE_PARK_INDEX, mIndex);
        bundle.putString(AppConstant.BUNDLE_PARK_LEVEL_NAME, "不合格");
        ActTransAnimUtils.startActionFadeInFadeOut(ChartOneActivity.this, ChartTwoActivity.class, bundle);
    }

    // 无效
    @OnClick(R.id.ll_level_e)
    public void clickLevelE() {
        if (mParksBean.getL5Sum() == 0) {
            return;
        }
        // 打包数据,传递并跳转到图表页面
        Bundle bundle = new Bundle();
        bundle.putInt(AppConstant.BUNDLE_PARK_INDEX, mIndex);
        bundle.putString(AppConstant.BUNDLE_PARK_LEVEL_NAME, "无效");
        ActTransAnimUtils.startActionFadeInFadeOut(ChartOneActivity.this, ChartTwoActivity.class, bundle);
    }

    /*--------------------------------------------------------------------------------
     *                          系统键处理
     ---------------------------------------------------------------------------------*/
    /**
     * 监听主页键,返回键
     *
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            // 返回
            ActTransAnimUtils.finishActionFadeOut(this);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

}
